import React, { useState, useEffect, useMemo } from "react";
// 引入模拟数据和API
import {
  mockVariables,
  mockSampleData,
  SystemVariableConfigMock,
  EntityMocks,
} from "@/mock/systemVariables";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { useToast } from "@/components/ui/use-toast";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import {
  Book,
  RefreshCw,
  Search,
  Check,
  AlertTriangle,
  Trash2,
  ListPlus,
  ListX,
  ChevronDown,
  ChevronRight,
  Copy,
  Code2,
  Edit3,
  Save,
  X,
} from "lucide-react";

// 修改实体映射为使用模拟实体
const ENTITY_MAP = {
  Project: {
    entity: EntityMocks.Project,
    schema: EntityMocks.Project.schema,
    prefix: "project_",
  },
  CrossingPoint: {
    entity: EntityMocks.CrossingPoint,
    schema: EntityMocks.CrossingPoint.schema,
    prefix: "crossing_",
  },
  ConstructionScheme: {
    entity: EntityMocks.ConstructionScheme,
    schema: EntityMocks.ConstructionScheme.schema,
    prefix: "scheme_",
  },
  System: {
    schema: () => ({
      properties: {
        current_date: { type: "string", description: "当前日期" },
        generator: { type: "string", description: "文档生成人" },
      },
    }),
    prefix: "system_",
  },
};

const CATEGORY_MAP = {
  Project: { name: "项目信息", icon: "📁" },
  CrossingPoint: { name: "跨越点信息", icon: "📍" },
  ConstructionScheme: { name: "施工方案信息", icon: "📄" },
  System: { name: "系统信息", icon: "💻" },
};

// 施工方案二级分类映射
const SCHEME_SUBCATEGORY_MAP = {
  // 基本信息
  schemeName: "基本信息",
  scheme_version: "基本信息",
  scheme_approvalStatus: "基本信息",
  scheme_constructionMethod: "基本信息",
  scheme_methodReasoning: "基本信息",
  scheme_construction_startDate: "基本信息",
  scheme_construction_endDate: "基本信息",
  scheme_totalDuration: "基本信息",
  scheme_costEstimation: "基本信息",
  scheme_weatherRequirements: "基本信息",

  // 审批信息
  scheme_approver: "审批信息",
  scheme_approvalDate: "审批信息",

  // 工作内容
  scheme_scopeOfWork: "工作内容",
  scheme_siteLayoutPlan: "工作内容",
  scheme_compilationBasis: "工作内容",
  scheme_acceptanceCriteria: "工作内容",

  // 施工步骤
  scheme_constructionSteps: "施工步骤",

  // 资源配置
  scheme_requiredMaterials: "资源配置",
  scheme_requiredPersonnel: "资源配置",
  scheme_requiredEquipment: "资源配置",
  scheme_requiredVehicles: "资源配置",

  // 安全措施
  scheme_schemeLevelSafetyMeasures: "安全措施",
  scheme_riskAssessment: "安全措施",

  // 质量措施
  scheme_schemeLevelQualityMeasures: "质量措施",
  scheme_qualityIssues: "质量措施",

  // 环境措施
  scheme_environmentalImpact: "环境措施",
  scheme_schemeLevelEnvironmentalMeasures: "环境措施",

  // 应急预案
  scheme_emergencyPlan: "应急预案",
  scheme_emergencyContacts: "应急预案",
  scheme_emergencyResponseMeasures: "应急预案",
  scheme_emergencyReportingProcess: "应急预案",

  // 专项作业 - 带电跨越
  scheme_liveWorkVoltageLevel: "专项作业-带电跨越",
  scheme_liveWorkSafetyDistance: "专项作业-带电跨越",
  scheme_liveWorkContactUnit: "专项作业-带电跨越",
  scheme_liveWorkSupervisor: "专项作业-带电跨越",
  scheme_liveWorkContactPhone: "专项作业-带电跨越",
  scheme_liveWorkTools: "专项作业-带电跨越",
  scheme_liveWorkSafetyMeasures: "专项作业-带电跨越",

  // 专项作业 - 停电跨越
  scheme_powerOutageScope: "专项作业-停电跨越",
  scheme_powerOutageDuration: "专项作业-停电跨越",
  scheme_powerOutageDispatchUnit: "专项作业-停电跨越",
  scheme_powerOutageDispatcher: "专项作业-停电跨越",
  scheme_powerOutageDispatcherPhone: "专项作业-停电跨越",
  scheme_powerOutageRequestTime: "专项作业-停电跨越",
  scheme_powerOutageRestoreTime: "专项作业-停电跨越",
  scheme_powerOutageSafetyMeasures: "专项作业-停电跨越",
  scheme_groundingWirePositions: "专项作业-停电跨越",

  // 专项作业 - 交通管制
  scheme_roadClosureType: "专项作业-交通管制",
  scheme_roadClosureDuration: "专项作业-交通管制",
  scheme_roadClosurePoliceUnit: "专项作业-交通管制",
  scheme_roadClosurePoliceContact: "专项作业-交通管制",
  scheme_roadClosurePolicePhone: "专项作业-交通管制",
  scheme_roadClosureDetourRoute: "专项作业-交通管制",
  scheme_roadClosureStakeNumber: "专项作业-交通管制",
  scheme_roadClosurePlan: "专项作业-交通管制",
  scheme_roadClosureEmergencyPlan: "专项作业-交通管制",

  // 专项作业 - 铁路管制
  scheme_railwayLineName: "专项作业-铁路管制",
  scheme_trafficControlType: "专项作业-铁路管制",
  scheme_trafficControlTimeWindow: "专项作业-铁路管制",
  scheme_trafficControlSpeedLimit: "专项作业-铁路管制",
  scheme_railwayDispatchUnit: "专项作业-铁路管制",
  scheme_railwayDispatcherContact: "专项作业-铁路管制",
  scheme_railwayDispatcherPhone: "专项作业-铁路管制",
  scheme_railwayProtectionMeasures: "专项作业-铁路管制",
  scheme_trafficControlPlan: "专项作业-铁路管制",

  // 专项作业 - 水域管制
  scheme_waterwayName: "专项作业-水域管制",
  scheme_waterway_level: "专项作业-水域管制",
  scheme_navigationControlRange: "专项作业-水域管制",
  scheme_navigationControlDuration: "专项作业-水域管制",
  scheme_maritimeContactUnit: "专项作业-水域管制",
  scheme_maritimeContact: "专项作业-水域管制",
  scheme_maritimeContactPhone: "专项作业-水域管制",
  scheme_waterWorkSafetyMeasures: "专项作业-水域管制",
  scheme_navigationControlPlan: "专项作业-水域管制",

  // 技术计算
  scheme_nettingWidth: "技术计算",
  scheme_nettingExtensionLength: "技术计算",
  scheme_calculatedNettingLength: "技术计算",
  scheme_tensionCalculationInputs: "技术计算",
  scheme_conductorType: "技术计算",
  scheme_spanLengthForTensionCheck: "技术计算",
  scheme_designTension: "技术计算",
  scheme_calculatedActualTension: "技术计算",

  // 人员配置
  scheme_schemePersonnel: "人员配置",
  scheme_coordinationDepartments: "人员配置",
  scheme_emergencyContactInfo: "人员配置",

  // 文档管理
  scheme_documentTemplateId: "文档管理",
  scheme_cachedWordDocumentUrl: "文档管理",
  scheme_cachedDocumentFilename: "文档管理",
  scheme_lastDocumentGenerated: "文档管理",
};

// 生成示例代码的函数（保持不变）
const generateExampleCode = (variable, sampleValue) => {
  const { variable_key, data_type, source_field } = variable;
  const basicUsage = `{{${variable_key}}}`;

  // 优先级1: 使用真实数据样本生成示例
  if (sampleValue !== null && sampleValue !== undefined && sampleValue !== "") {
    if (
      data_type === "array" &&
      Array.isArray(sampleValue) &&
      sampleValue.length > 0
    ) {
      const firstItem = sampleValue[0];
      if (
        typeof firstItem === "object" &&
        firstItem !== null &&
        !Array.isArray(firstItem)
      ) {
        const keys = Object.keys(firstItem).slice(0, 3); // 取前3个键作为示例
        const properties = keys.map((k) => `${k}: {{${k}}}`).join(", ");
        return `{{#each ${variable_key}}}\n  - ${properties}\n{{/each}}`;
      } else {
        return `{{#each ${variable_key}}}\n  - {{this}}\n{{/each}}`;
      }
    }
    if (
      data_type === "object" &&
      typeof sampleValue === "object" &&
      sampleValue !== null &&
      !Array.isArray(sampleValue) &&
      Object.keys(sampleValue).length > 0
    ) {
      // 递归查找对象内部的路径
      const generateObjectPaths = (
        obj,
        currentPath = [],
        paths = [],
        depth = 0,
        limit = 3
      ) => {
        if (paths.length >= limit) return paths; // 限制示例数量
        if (depth > 1) return paths; // 限制递归深度

        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            const newPath = [...currentPath, key];
            const value = obj[key];

            if (
              typeof value === "object" &&
              value !== null &&
              !Array.isArray(value) &&
              Object.keys(value).length > 0
            ) {
              generateObjectPaths(value, newPath, paths, depth + 1, limit);
            } else {
              if (paths.length < limit) {
                paths.push(`{{${variable_key}.${newPath.join(".")}}}`);
              } else {
                return paths;
              }
            }
          }
        }
        return paths;
      };

      const paths = generateObjectPaths(sampleValue);
      if (paths.length > 0) {
        return `// 访问对象属性示例:\n${paths.join("\n")}`;
      }
    }
  }

  // 优先级2: 回退到旧的通用逻辑
  switch (data_type) {
    case "array":
      return `{{#each ${variable_key}}}\n  - {{name}}: {{quantity}}{{unit}}\n{{/each}}\n\n或者简单列表：\n{{#each ${variable_key}}}\n  - {{.}}\n{{/each}}`;

    case "object":
      if (
        source_field.includes("contacts") ||
        source_field.includes("emergency")
      ) {
        return `医院: {{${variable_key}.hospital.name}} - {{${variable_key}.hospital.phone}}\n消防: {{${variable_key}.fireDepartment.name}} - {{${variable_key}.fireDepartment.phone}}`;
      } else if (source_field.includes("tower")) {
        return `杆塔编号: {{${variable_key}.towerNumber}}\n杆塔类型: {{${variable_key}.towerType}}\n杆塔高度: {{${variable_key}.towerHeight}}m`;
      }
      return `{{${variable_key}.property_name}}`;

    case "boolean":
      return `{{#if ${variable_key}}}\n  需要特殊处理\n{{else}}\n  无需特殊处理\n{{/if}}`;

    case "date":
      return `${basicUsage} (将自动格式化为日期格式)`;

    case "number":
      if (source_field.includes("duration") || source_field.includes("time")) {
        return `${basicUsage}小时`;
      } else if (
        source_field.includes("cost") ||
        source_field.includes("estimation")
      ) {
        return `${basicUsage}万元`;
      } else if (
        source_field.includes("length") ||
        source_field.includes("distance") ||
        source_field.includes("height")
      ) {
        return `${basicUsage}米`;
      }
      return basicUsage;

    default:
      return basicUsage;
  }
};

// 变量项组件（保持不变）
const VariableItem = ({ variable, onDelete, onCopy, onEdit }) => {
  const [copiedKey, setCopiedKey] = useState(false);
  const [copiedCode, setCopiedCode] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editData, setEditData] = useState(variable);

  const handleCopy = (text, type) => {
    navigator.clipboard.writeText(text);
    if (type === "key") {
      setCopiedKey(true);
      setTimeout(() => setCopiedKey(false), 1500);
    } else {
      setCopiedCode(true);
      setTimeout(() => setCopiedCode(false), 1500);
    }
    if (onCopy) onCopy();
  };

  const handleSave = () => {
    onEdit(editData);
    setIsEditing(false);
  };

  const handleCancel = () => {
    setEditData(variable);
    setIsEditing(false);
  };

  return (
    <div
      className={`p-4 border rounded-lg hover:bg-gray-50 transition-colors ${
        variable.is_deprecated ? "bg-red-50 border-red-200" : "bg-white"
      }`}
    >
      <div className="flex items-start justify-between">
        <div className="flex-1 min-w-0">
          <div
            className="font-mono text-sm text-blue-600 mb-2 flex items-center gap-2 cursor-pointer"
            title="点击复制变量"
            onClick={() => handleCopy(`{{${variable.variable_key}}}`, "key")}
          >
            <span className="break-all">{`{{${variable.variable_key}}}`}</span>
            {copiedKey ? (
              <Check className="w-4 h-4 text-green-600 flex-shrink-0" />
            ) : (
              <Copy className="w-4 h-4 text-gray-400 group-hover:text-blue-600 flex-shrink-0" />
            )}
          </div>

          {isEditing ? (
            <div className="space-y-3">
              <Input
                value={editData.description}
                onChange={(e) =>
                  setEditData({ ...editData, description: e.target.value })
                }
                placeholder="变量描述"
                className="text-sm"
              />
              <Input
                value={editData.example}
                onChange={(e) =>
                  setEditData({ ...editData, example: e.target.value })
                }
                placeholder="示例值"
                className="text-sm"
              />
              <textarea
                value={editData.example_code || ""}
                onChange={(e) =>
                  setEditData({ ...editData, example_code: e.target.value })
                }
                placeholder="示例代码"
                className="w-full p-2 text-xs font-mono border rounded resize-none"
                rows="3"
              />
              <div className="flex gap-2">
                <Button size="sm" onClick={handleSave}>
                  <Save className="w-3 h-3 mr-1" />
                  保存
                </Button>
                <Button size="sm" variant="outline" onClick={handleCancel}>
                  <X className="w-3 h-3 mr-1" />
                  取消
                </Button>
              </div>
            </div>
          ) : (
            <>
              <p className="text-sm text-gray-600 mb-2 break-words">
                {variable.description}
              </p>

              {variable.is_deprecated && (
                <div className="text-xs text-red-600 flex items-center gap-1 mb-2">
                  <AlertTriangle className="w-4 h-4" />
                  <span>此变量已弃用，源字段可能已不存在。</span>
                </div>
              )}

              {/* 示例代码 */}
              <div className="bg-gray-50 p-2 rounded-md border mb-2">
                <div className="flex items-center justify-between mb-1">
                  <span className="text-xs font-semibold text-gray-700">
                    模板用法示例:
                  </span>
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-6 px-2"
                    onClick={() =>
                      handleCopy(
                        variable.example_code || generateExampleCode(variable),
                        "code"
                      )
                    }
                  >
                    {copiedCode ? (
                      <Check className="w-3 h-3 text-green-600" />
                    ) : (
                      <Copy className="w-3 h-3 text-gray-400" />
                    )}
                  </Button>
                </div>
                <pre className="text-xs font-mono text-gray-700 whitespace-pre-wrap break-words overflow-x-auto">
                  {variable.example_code || generateExampleCode(variable)}
                </pre>
              </div>

              <div className="flex items-center justify-between text-xs text-gray-500">
                <span>
                  来源: {variable.source_entity} / {variable.source_field}
                </span>
                <div className="flex items-center gap-2">
                  {variable.is_deprecated ? (
                    <Badge variant="destructive" className="text-xs">
                      已弃用
                    </Badge>
                  ) : (
                    <Badge
                      variant="default"
                      className="bg-green-100 text-green-800 text-xs"
                    >
                      活跃
                    </Badge>
                  )}
                  <Button
                    size="sm"
                    variant="ghost"
                    onClick={() => setIsEditing(true)}
                    className="h-6 px-2"
                  >
                    <Edit3 className="w-3 h-3" />
                  </Button>
                  {variable.is_deprecated && (
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onDelete(variable.id)}
                      className="p-1 h-6 w-6"
                    >
                      <Trash2 className="w-3 h-3 text-red-500" />
                    </Button>
                  )}
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};

// 左侧导航组件（保持不变）
const CategoryNavigation = ({
  groupedVariables,
  selectedCategory,
  selectedSubCategory,
  onCategorySelect,
  onSubCategorySelect,
  searchTerm,
}) => {
  const [expandedCategories, setExpandedCategories] = useState(
    Object.keys(groupedVariables).reduce(
      (acc, cat) => ({ ...acc, [cat]: true }),
      {}
    )
  );

  const toggleCategory = (category) => {
    console.log(category, "category");

    setExpandedCategories((prev) => ({ ...prev, [category]: !prev[category] }));
  };

  return (
    <div className="w-80 bg-white border-r border-gray-200 p-4 overflow-y-auto">
      <div className="space-y-2">
        {Object.entries(groupedVariables).map(
          ([categoryName, categoryData]) => (
            <Collapsible
              key={categoryName}
              open={searchTerm ? true : expandedCategories[categoryName]}
              onOpenChange={() => toggleCategory(categoryName)}
            >
              <CollapsibleTrigger asChild>
                <Button
                  variant="ghost"
                  className={`w-full justify-between p-3 h-auto hover:bg-blue-50 ${
                    selectedCategory === categoryName ? "bg-blue-100" : ""
                  }`}
                  onClick={() => {
                    onCategorySelect(categoryName);
                    onSubCategorySelect(null);
                  }}
                >
                  <div className="flex items-center gap-3 text-left">
                    <span className="text-xl">{categoryData.icon}</span>
                    <div>
                      <div className="font-semibold text-gray-800">
                        {categoryName}
                      </div>
                      <p className="text-xs text-gray-500 font-normal">
                        {categoryData.variables.length} 个变量
                      </p>
                    </div>
                  </div>
                  {searchTerm ? null : expandedCategories[categoryName] ? (
                    <ChevronDown className="w-5 h-5" />
                  ) : (
                    <ChevronRight className="w-5 h-5" />
                  )}
                </Button>
              </CollapsibleTrigger>
              <CollapsibleContent className="space-y-1 pl-4">
                {categoryData.subGroups ? (
                  // 有二级分组（施工方案信息）
                  Object.entries(categoryData.subGroups).map(
                    ([subCategoryName, subVariables]) => (
                      <Button
                        key={subCategoryName}
                        variant="ghost"
                        className={`w-full justify-start p-2 h-auto text-left hover:bg-gray-100 ${
                          selectedSubCategory === subCategoryName
                            ? "bg-gray-200"
                            : ""
                        }`}
                        onClick={() => {
                          onCategorySelect(categoryName);
                          onSubCategorySelect(subCategoryName);
                        }}
                      >
                        <div className="flex items-center justify-between w-full">
                          <span className="font-medium text-gray-700 text-sm">
                            {subCategoryName}
                          </span>
                          <Badge
                            variant="outline"
                            className="text-xs text-gray-500"
                          >
                            {subVariables.length}
                          </Badge>
                        </div>
                      </Button>
                    )
                  )
                ) : (
                  // 无二级分组，显示"全部"选项
                  <Button
                    variant="ghost"
                    className={`w-full justify-start p-2 h-auto text-left hover:bg-gray-100 ${
                      selectedCategory === categoryName && !selectedSubCategory
                        ? "bg-gray-200"
                        : ""
                    }`}
                    onClick={() => {
                      onCategorySelect(categoryName);
                      onSubCategorySelect(null);
                    }}
                  >
                    <span className="text-sm text-gray-600">全部</span>
                  </Button>
                )}
              </CollapsibleContent>
            </Collapsible>
          )
        )}
      </div>
    </div>
  );
};

export default function SystemVariableConfigPage() {
  const [variables, setVariables] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSyncing, setIsSyncing] = useState(false);
  const [syncProgress, setSyncProgress] = useState({
    current: 0,
    total: 0,
    status: "",
  });
  const [searchTerm, setSearchTerm] = useState("");
  const [selectedCategory, setSelectedCategory] = useState("");
  const [selectedSubCategory, setSelectedSubCategory] = useState(null);
  const { toast } = useToast();

  useEffect(() => {
    loadVariables();
  }, []);

  // 修改为使用模拟API加载变量
  const loadVariables = async () => {
    try {
      // 使用模拟API替代真实接口调用
      const data = await SystemVariableConfigMock.list("-created_date");
      setVariables(data || []);

      // 自动选择第一个分类
      if (data && data.length > 0) {
        const firstCategory = data[0].category;
        if (!selectedCategory) {
          setSelectedCategory(firstCategory);
        }
      }
    } catch (error) {
      toast({
        variant: "destructive",
        title: "加载失败",
        description: "加载变量配置失败: " + error.message,
      });
    } finally {
      setIsLoading(false);
    }
  };

  // 添加延迟函数避免速率限制
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  // 修改同步函数使用模拟数据
  const handleSyncWithSchemas = async () => {
    setIsSyncing(true);
    setSyncProgress({ current: 0, total: 0, status: "正在分析实体结构..." });

    let addedCount = 0;
    let deprecatedCount = 0;
    let reactivatedCount = 0;

    try {
      // 使用模拟API获取现有变量
      const existingVars = await SystemVariableConfigMock.list();
      const existingVarMap = new Map(
        existingVars.map((v) => [v.variable_key, v])
      );
      const currentSchemaVarKeys = new Set();
      const newVariablesToCreate = [];

      // 获取每个实体的样本数据（使用预定义的模拟样本数据）
      const sampleData = mockSampleData;
      const entityNames = Object.keys(ENTITY_MAP);
      setSyncProgress({
        current: 0,
        total: entityNames.length,
        status: "正在获取样本数据...",
      });
      let sampleDataFetchedCount = 0;

      for (const entityName of entityNames) {
        sampleDataFetchedCount++;
        setSyncProgress({
          current: sampleDataFetchedCount,
          total: entityNames.length,
          status: `正在获取 ${entityName} 样本数据...`,
        });
        await delay(50); // 模拟网络延迟
      }

      // 第一步：分析所有实体，收集需要创建的变量
      const entityEntries = Object.entries(ENTITY_MAP);
      setSyncProgress({
        current: 0,
        total: entityEntries.length,
        status: "分析实体结构...",
      });

      let entityIndex = 0;
      for (const [entityName, { schema, prefix }] of entityEntries) {
        entityIndex++;
        setSyncProgress({
          current: entityIndex,
          total: entityEntries.length,
          status: `分析 ${entityName} 实体...`,
        });

        try {
          const entitySchema = await schema();
          const properties = entitySchema.properties || {};

          for (const [field, details] of Object.entries(properties)) {
            const variableKey = `${prefix}${field}`;
            currentSchemaVarKeys.add(variableKey);

            const existingVar = existingVarMap.get(variableKey);

            if (existingVar) {
              if (existingVar.is_deprecated) {
                // 重新激活已弃用变量
                try {
                  await SystemVariableConfigMock.update(existingVar.id, {
                    is_deprecated: false,
                  });
                  reactivatedCount++;
                  await delay(100);
                } catch (updateError) {
                  console.error(
                    `重新激活变量 ${variableKey} 失败:`,
                    updateError
                  );
                }
              }
            } else {
              // 创建新变量
              const sampleRecord = sampleData[entityName];
              const sampleValue = sampleRecord
                ? sampleRecord[field]
                : undefined;

              const getSampleValueString = (value) => {
                if (value === null || value === undefined || value === "")
                  return "无";
                if (
                  typeof value === "string" ||
                  typeof value === "number" ||
                  typeof value === "boolean"
                ) {
                  const strVal = String(value);
                  return strVal.length > 50
                    ? strVal.substring(0, 50) + "..."
                    : strVal;
                }
                if (Array.isArray(value)) return `数组(共${value.length}项)`;
                if (typeof value === "object")
                  return `对象(${Object.keys(value).length}个属性)`;
                return "未知类型";
              };

              const categoryInfo = CATEGORY_MAP[entityName] || {
                name: "其他",
                icon: "❓",
              };
              const newVariable = {
                variable_key: variableKey,
                description:
                  details.description || `来自${entityName}的${field}字段`,
                example: `示例: ${getSampleValueString(sampleValue)}`,
                example_code: generateExampleCode(
                  {
                    variable_key: variableKey,
                    data_type: details.type || "string",
                    source_field: field,
                  },
                  sampleValue
                ),
                category: categoryInfo.name,
                category_icon: categoryInfo.icon,
                source_entity: entityName,
                source_field: field,
                data_type: details.type || "string",
                is_deprecated: false,
              };
              newVariablesToCreate.push(newVariable);
            }
          }
        } catch (schemaError) {
          console.error(`获取 ${entityName} schema 失败:`, schemaError);
        }
      }

      // 第二步：批量创建新变量
      if (newVariablesToCreate.length > 0) {
        setSyncProgress({
          current: 0,
          total: newVariablesToCreate.length,
          status: "创建新变量...",
        });

        // 每批处理5个
        const batchSize = 5;
        let createdInThisPhase = 0;
        for (let i = 0; i < newVariablesToCreate.length; i += batchSize) {
          const batch = newVariablesToCreate.slice(i, i + batchSize);

          try {
            // 使用模拟批量创建方法
            await SystemVariableConfigMock.bulkCreate(batch);
            addedCount += batch.length;
            createdInThisPhase += batch.length;
            setSyncProgress({
              current: createdInThisPhase,
              total: newVariablesToCreate.length,
              status: `创建新变量... (批次 ${Math.ceil(
                (i + batchSize) / batchSize
              )}/${Math.ceil(newVariablesToCreate.length / batchSize)})`,
            });
          } catch (batchError) {
            console.error("批量创建变量失败，尝试逐个创建:", batchError);

            // 逐个创建
            for (const variable of batch) {
              try {
                await SystemVariableConfigMock.create(variable);
                addedCount++;
                createdInThisPhase++;
                setSyncProgress({
                  current: createdInThisPhase,
                  total: newVariablesToCreate.length,
                  status: `创建变量: ${variable.variable_key} (回退)`,
                });
                await delay(200);
              } catch (individualError) {
                console.error(
                  `创建变量 ${variable.variable_key} 失败:`,
                  individualError
                );
              }
            }
          }

          // 批次间延迟
          if (i + batchSize < newVariablesToCreate.length) {
            await delay(500);
          }
        }
      }

      // 第三步：标记弃用的变量
      setSyncProgress({ current: 0, total: 0, status: "标记弃用变量..." });

      let deprecatedProcessedCount = 0;
      const variablesToDeprecate = existingVars.filter(
        (v) => !currentSchemaVarKeys.has(v.variable_key) && !v.is_deprecated
      );
      setSyncProgress({
        current: 0,
        total: variablesToDeprecate.length,
        status: "标记弃用变量...",
      });

      for (const existingVar of variablesToDeprecate) {
        try {
          await SystemVariableConfigMock.update(existingVar.id, {
            is_deprecated: true,
          });
          deprecatedCount++;
          deprecatedProcessedCount++;
          setSyncProgress({
            current: deprecatedProcessedCount,
            total: variablesToDeprecate.length,
            status: `标记弃用: ${existingVar.variable_key}`,
          });
          await delay(100);
        } catch (updateError) {
          console.error(
            `标记变量 ${existingVar.variable_key} 为弃用失败:`,
            updateError
          );
        }
      }

      toast({
        title: "同步成功",
        description: `新增 ${addedCount} 个, 重新激活 ${reactivatedCount} 个, 弃用 ${deprecatedCount} 个变量。`,
        duration: 3000,
      });
      await loadVariables();
    } catch (error) {
      console.error("同步过程出错:", error);
      toast({
        variant: "destructive",
        title: "同步失败",
        description: "与实体同步变量时出错: " + error.message,
      });
    } finally {
      setIsSyncing(false);
      setSyncProgress({ current: 0, total: 0, status: "" });
    }
  };

  // 修改删除函数使用模拟API
  const handleDeleteVariable = async (id) => {
    if (window.confirm("确定要永久删除这个变量配置吗？")) {
      try {
        await SystemVariableConfigMock.delete(id);
        toast({ title: "删除成功" });
        loadVariables();
      } catch (error) {
        toast({
          variant: "destructive",
          title: "删除失败",
          description: error.message,
        });
      }
    }
  };

  // 修改编辑函数使用模拟API
  const handleEditVariable = async (updatedVariable) => {
    try {
      await SystemVariableConfigMock.update(
        updatedVariable.id,
        updatedVariable
      );
      toast({ title: "更新成功" });
      loadVariables();
    } catch (error) {
      toast({
        variant: "destructive",
        title: "更新失败",
        description: error.message,
      });
    }
  };

  const handleCopyVariable = () => {
    toast({
      title: "变量已复制",
      description: "变量已复制到剪贴板，可在模板中直接使用。",
      duration: 3000,
    });
  };

  // 分组和过滤变量（修复排序时可能出现的undefined问题）
  const groupedAndFilteredVariables = useMemo(() => {
    const lowercasedFilter = searchTerm.toLowerCase();

    const filtered = searchTerm
      ? variables.filter(
          (v) =>
            v?.variable_key?.toLowerCase().includes(lowercasedFilter) ||
            v?.description?.toLowerCase().includes(lowercasedFilter) ||
            v?.category?.toLowerCase().includes(lowercasedFilter) ||
            (v?.source_entity &&
              v.source_entity.toLowerCase().includes(lowercasedFilter)) ||
            (v?.source_field &&
              v.source_field.toLowerCase().includes(lowercasedFilter))
        )
      : variables;

    // 修复排序错误：先过滤掉无效元素
    const validFiltered = filtered.filter((v) => v && v.variable_key);
    validFiltered.sort((a, b) => a.variable_key.localeCompare(b.variable_key));

    // 按分类分组
    const grouped = validFiltered.reduce((acc, v) => {
      const category = v.category || "未分类";
      if (!acc[category]) {
        acc[category] = {
          icon: CATEGORY_MAP[v.source_entity]?.icon || "❓",
          variables: [],
        };
      }
      acc[category].variables.push(v);
      return acc;
    }, {});

    // 对施工方案信息进行二级分组
    Object.keys(grouped).forEach((category) => {
      if (category === "施工方案信息") {
        const subGrouped = grouped[category].variables.reduce((subAcc, v) => {
          const subCategory = SCHEME_SUBCATEGORY_MAP[v.variable_key] || "其他";
          if (!subAcc[subCategory]) {
            subAcc[subCategory] = [];
          }
          subAcc[subCategory].push(v);
          return subAcc;
        }, {});
        // 按名称排序二级分类
        grouped[category].subGroups = Object.fromEntries(
          Object.entries(subGrouped).sort(([nameA], [nameB]) =>
            nameA.localeCompare(nameB)
          )
        );
      }
    });

    // 按名称排序顶级分类
    return Object.fromEntries(
      Object.entries(grouped).sort(([nameA], [nameB]) =>
        nameA.localeCompare(nameB)
      )
    );
  }, [variables, searchTerm]);

  // 获取当前显示的变量列表
  const currentVariables = useMemo(() => {
    if (!selectedCategory) return [];

    const categoryData = groupedAndFilteredVariables[selectedCategory];
    if (!categoryData) return [];

    if (selectedSubCategory && categoryData.subGroups) {
      return categoryData.subGroups[selectedSubCategory] || [];
    }

    return categoryData.variables || [];
  }, [groupedAndFilteredVariables, selectedCategory, selectedSubCategory]);

  // 页面渲染（保持不变）
  return (
    <div className="p-6 bg-gray-50 min-h-screen">
      <Card className="max-w-full mx-auto h-[calc(100vh-100px)]">
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2 text-2xl">
                <Book className="w-6 h-6 text-blue-600" />
                变量配置管理
              </CardTitle>
              <p className="text-gray-600 mt-1">
                管理并同步文档模板中使用的变量
              </p>
            </div>
            <Button onClick={handleSyncWithSchemas} disabled={isSyncing}>
              <RefreshCw
                className={`w-4 h-4 mr-2 ${isSyncing ? "animate-spin" : ""}`}
              />
              {isSyncing ? "同步中..." : "与实体同步"}
            </Button>
          </div>
        </CardHeader>
        <CardContent className="p-0 h-full">
          <Alert className="m-6 mb-4 border-blue-200 bg-blue-50">
            <AlertTriangle className="h-4 w-4" />
            <AlertTitle className="text-blue-800">工作原理</AlertTitle>
            <AlertDescription className="text-blue-700">
              点击【与实体同步】按钮，系统将自动扫描项目、跨越点、施工方案等实体结构，
              自动添加新变量、并标记实体中已不存在的旧变量为"已弃用"。
            </AlertDescription>
          </Alert>

          {/* 同步进度显示 */}
          {isSyncing && (
            <Alert className="m-6 mb-4 border-orange-200 bg-orange-50">
              <RefreshCw className="h-4 w-4 animate-spin" />
              <AlertTitle className="text-orange-800">正在同步</AlertTitle>
              <AlertDescription className="text-orange-700">
                {syncProgress.status}
                {syncProgress.total > 0 && (
                  <div className="mt-2">
                    <div className="w-full bg-orange-200 rounded-full h-2">
                      <div
                        className="bg-orange-600 h-2 rounded-full transition-all duration-300"
                        style={{
                          width: `${
                            (syncProgress.current / syncProgress.total) * 100
                          }%`,
                        }}
                      ></div>
                    </div>
                    <p className="text-xs mt-1">
                      {syncProgress.current}/{syncProgress.total}
                    </p>
                  </div>
                )}
              </AlertDescription>
            </Alert>
          )}

          <div className="flex h-full">
            {/* 左侧分类导航 */}
            <CategoryNavigation
              groupedVariables={groupedAndFilteredVariables}
              selectedCategory={selectedCategory}
              selectedSubCategory={selectedSubCategory}
              onCategorySelect={setSelectedCategory}
              onSubCategorySelect={setSelectedSubCategory}
              searchTerm={searchTerm}
            />

            {/* 右侧变量列表 */}
            <div className="flex-1 flex flex-col">
              {/* 搜索栏和统计 */}
              <div className="flex justify-between items-center p-6 border-b">
                <div className="relative w-full max-w-sm">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4" />
                  <Input
                    placeholder="搜索变量、描述或分类..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
                <div className="flex items-center gap-6 text-sm">
                  <div className="flex items-center gap-2">
                    <ListPlus className="w-5 h-5 text-green-500" />
                    <span>
                      活跃: {variables.filter((v) => !v.is_deprecated).length}
                    </span>
                  </div>
                  <div className="flex items-center gap-2">
                    <ListX className="w-5 h-5 text-red-500" />
                    <span>
                      已弃用: {variables.filter((v) => v.is_deprecated).length}
                    </span>
                  </div>
                </div>
              </div>

              {/* 变量列表内容 */}
              <div className="flex-1 overflow-y-auto p-6">
                {isLoading ? (
                  <div className="text-center py-8 text-gray-500">
                    加载中...
                  </div>
                ) : currentVariables.length > 0 ? (
                  <div className="space-y-3">
                    {currentVariables.map((variable) => (
                      <VariableItem
                        key={variable.id}
                        variable={variable}
                        onDelete={handleDeleteVariable}
                        onCopy={handleCopyVariable}
                        onEdit={handleEditVariable}
                      />
                    ))}
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500">
                    <p>未找到匹配的变量</p>
                  </div>
                )}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
